/* eslint-disable array-bracket-spacing */
/* eslint-disable no-dupe-class-members */
/* eslint-disable indent */
'use strict'

const Service = require('egg').Service
const dayjs = require('dayjs')
const { Op } = require('sequelize')

// 信息要返回的字段
const attributes = ['id', 'm_bid', 'pid', 'recharge_time', 'amount']
const member_attributes = ['id', 'mid', 'openid', 'unionid', 'phone', 'nickname', 'avatar', 'sex', 'birthday', 'register_time', 'last_login_time', 'level_name', 'subscribe', 'subscribe_time', 'pid', 'card_id', 'balance', 'recharge_amount', 'consume_time', 'week_count', 'count', 'status']
const place_attributes = ['barname', 'barcode']

class RechargeService extends Service {

    // 查询所有列表
    async getRechargeList(params) {
        const { model, helper } = this.ctx
        const currentPage = params?.pageIndex ?? 1
        const pageSize = params?.pageSize ?? 50
        const where = {}
        if (params.pid) {
            where.pid = params.pid
        }
        if (params.start_time && params.end_time) {
            where.recharge_time = {
                [Op.between]: [params.start_time, params.end_time]
            }
        }

        return await model.Recharge.findAndCountAll({
            where,
            offset: (currentPage - 1) * pageSize, // 计算分页偏移量
            limit: pageSize,
            attributes,
            include: [
                {
                    model: model.Place,
                    // as: 'place',
                    attributes: place_attributes
                },
                {
                    model: model.Member,
                    // as: 'member',
                    attributes: member_attributes
                }
            ],
            order: [
                ['recharge_time', 'DESC']
            ]
        })
            .then(async result => {
                if (result) {
                    return {
                        list: result.rows,
                        total: result.count
                    }
                }
                helper.failed(1008, null, '查询上机记录失败')
                return false
            })
            .catch(async error => {
                // console.log('查询上机记录失败', error)
                if (error?.original?.sqlMessage) {
                    helper.failed(1001, null, error?.original?.sqlMessage)
                } else if (error?.errors) {
                    helper.failed(1001, null, JSON.stringify(error.errors))
                } else {
                    helper.failed(1001, null, JSON.stringify(error))
                }
                return false
            })
    }

    // 新增
    async createRecharge(params) {
        const { model, helper, logger } = this.ctx
        let flag = 0
        // 使用事务
        const t = await model.transaction()
        try {

            // 写入会员表
            const [member, isCreated] = await model.Member.findOrCreate({
                where: {
                    mid: params.mid,
                    pid: params.pid
                },
                defaults: {
                    ...params,
                    register_time: dayjs().format('YYYY-MM-DD HH:mm:ss'),
                    recharge_amount: params.amount, // 充值金额
                    balance: params.amount // 余额
                },
                transaction: t
            })
            if (!isCreated && member) {
                await member.update({
                    ...params,
                    balance: params.amount + params.balance,
                    recharge_amount: member.recharge_amount + params.amount // 充值金额
                }, {
                    transaction: t
                })
            }
            flag = 1

            // 查询充值记录是否已存在
            const result = await model.Recharge.findOne({
                where: {
                    pid: params.pid,
                    m_bid: member.id,
                    recharge_time: params.recharge_time,
                    amount: params.amount
                },
                // include: [
                //     {
                //         model: model.Member,
                //         where: {
                //             mid: params.mid
                //         }
                //     }
                // ],
                transaction: t,
                attributes
            })
            if (result) {
                await t.commit()
                helper.failed(1003, null, '充值记录已存在')
                return false
            }
            flag = 2

            // 写入充值记录表
            const record = await model.Recharge.create({
                ...params,
                m_bid: member.id
            }, {
                transaction: t
            })
            flag = 3

            await t.commit()
            flag = 4

            const res = await member.toJSON()
            res.computer_name = params?.computer_name ? params.computer_name : ''
            res.area_name = params?.area_name ? params.area_name : ''
            return res
        } catch (error) {
            await t.rollback() // 回滚

            if (error?.original?.sqlMessage) {
                logger.error(`充值操作失败   flag:[${flag}] pid:[${params.pid}] mid:[${params.mid}] ${error?.original?.sqlMessage}`)
                helper.failed(1001, null, error?.original?.sqlMessage)
            } else if (error?.errors) {
                logger.error(`充值操作失败   flag:[${flag}] pid:[${params.pid}] mid:[${params.mid}] ${JSON.stringify(error.errors)}`)
                helper.failed(1001, null, JSON.stringify(error.errors))
            } else {
                logger.error(`充值操作失败   flag:[${flag}] pid:[${params.pid}] mid:[${params.mid}] ${JSON.stringify(error)}`)
                helper.failed(1001, null, JSON.stringify(error))
            }

            return false
        }
    }

}

module.exports = RechargeService
